package com.hmtech.aup.presentation.home

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.hmtech.aup.R
import com.hmtech.aup.domain.vo.CategoryVO

class CategoryAdapter :
    ListAdapter<CategoryVO, CategoryAdapter.CategoryViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_category, parent, false)
        return CategoryViewHolder(view)
    }

    override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val titleTv: TextView = itemView.findViewById(R.id.tvTitle)
        private val stylesRv: RecyclerView = itemView.findViewById(R.id.rvStyles)
        private val styleItemAdapter = StyleItemAdapter()

        init {
            stylesRv.layoutManager = LinearLayoutManager(
                itemView.context,
                LinearLayoutManager.HORIZONTAL, false
            )
            stylesRv.adapter = styleItemAdapter
        }

        fun bind(item: CategoryVO) {
            titleTv.text = item.title
            styleItemAdapter.submitList(item.styles)
            Log.d("CategoryViewHolder", "Binding styles size: ${item.styles.size}")
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<CategoryVO>() {
        override fun areItemsTheSame(oldItem: CategoryVO, newItem: CategoryVO): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: CategoryVO, newItem: CategoryVO): Boolean {
            return oldItem == newItem
        }
    }
}